<?php


namespace api\app\controller;


use api\app\model\IndentModel;
use api\app\model\UserModel;
use api\app\model\WalletModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
    public function pay(Request $request)
    {
        $order_id = input('post.order_id');
        $userid = $request->hello;
        $indent = IndentModel::where('trade_no','=',$order_id)
            ->find();
        if(!$indent) {
            return error('订单不存在');
        }
        if($indent['status'] != 1) {
            return error('已支付');
        }
        $user = UserModel::where('id','=',$userid)
            ->find();
        if($user['wallet'] < $indent['total_price']){
            return error('余额不足');
        }
        Db::startTrans();
        $log = "";

        $res = "";
        try {
            $indent->wallet = $user['wallet'] - $indent['total_price'];
            $indent->pay_type="余额";
            $indent->status= 1;
            $log = $indent->save();
            $res = wallet_log($userid, $indent['total_price'], $user['wallet'], $user['wallet'] - $indent['total_price'], '购买',0);

        }catch (\Exception $e){
            Db::rollback();
        }
        if ($log && $res) {
            Db::commit();
            return success('成功');
        } else {
            Db::rollback();
            return error('失败');
        }
    }

}